
package com.kugou.game.sdk.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;

import java.util.HashSet;
import java.util.Hashtable;

/**
 * 描述:安装/卸载辅助类
 * 
 * @author chenys
 * @since 2013-10-24 下午2:17:03
 */
@SuppressLint("HandlerLeak")
public class InstallHelper {

    /**
     * 开始安装
     */
    public static final int STATE_INSTALL_START = 1;

    /**
     * 安装成功
     */
    public static final int STATE_INSTALL_SUCCESS = 2;

    /**
     * 安装失败
     */
    public static final int STATE_INSTALL_FAILE = 3;

    private static Context mContext;

    private static PackageManager mPackageManager;

    private static HandlerThread mHandlerThread;

    private static InstallHelper mInstallHelper;

    private static BackgroundHandler mBackgroundHandler;

    private static boolean mIsRoot;

    private static HashSet<String> mInstallingPackage;

    private static Hashtable<String, String> mNormalInstallingFile;

    private OnInstallStateListener mOnInstallStateListener;

    public static interface OnInstallStateListener {

        void onStart(String filePath, String packageName, int versionCode);

        void onSuccess(String filePath, String packageName, int versionCode);

        void onFaile(String filePath, String packageName, int versionCode, int faileType);

    }

    public void setOnInstallStateListener(OnInstallStateListener listener) {
        mOnInstallStateListener = listener;
    }

    private final int MSG_BACK_INSTALL_APK = 0X20;

    private final int MSG_BACK_INSTALL_GPK = 0X21;

    final class BackgroundHandler extends Handler {

        BackgroundHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_BACK_INSTALL_APK:
                    Bundle data = msg.getData();
                    // 安装包基本信息
                    final String filePath = data.getString("filePath");
                    final String packageName = data.getString("packageName");
                    final int versionCode = data.getInt("versionCode");
                    if (TextUtils.isEmpty(packageName)) {
                        handleApkInstall(filePath, "", versionCode);
                    } else {
                        handleApkInstall(filePath, packageName, versionCode);
                    }
                    break;
                case MSG_BACK_INSTALL_GPK:
                    Bundle data2 = msg.getData();
                    final String gpkFilePath = data2.getString("filePath");
                    final String apkFileName = data2.getString("apkFileName");

                    // handleGpkInstall(gpkFilePath, apkFileName);
                    break;
            }
        }
    }

    private InstallHelper() {
    }

    public static InstallHelper getInstance() {
        if (mInstallHelper == null) {
            mInstallHelper = new InstallHelper();
        }
        return mInstallHelper;
    }

    public void init(Context context) {
        mContext = context;
        mPackageManager = mContext.getPackageManager();
        mInstallingPackage = new HashSet<String>();
        mNormalInstallingFile = new Hashtable<String, String>();
        mHandlerThread = new HandlerThread("InstallHelper " + getClass().getSimpleName());
        mHandlerThread.start();
        mBackgroundHandler = new BackgroundHandler(mHandlerThread.getLooper());
    }

    /**
     * 安装APK
     * 
     * @param packageName
     * @param filePath
     */
    public void install(String filePath) {
        if (!TextUtils.isEmpty(filePath) && FileUtil.isFileExist(filePath)) {
            if (filePath.toLowerCase().endsWith(".gpk")) {
            } else {
                installApk(filePath);
            }
        }
    }

    /**
     * 安装APK文件
     * 
     * @param apkFilePath
     */
    public void installApk(String apkFilePath) {
        if (TextUtils.isEmpty(apkFilePath) || !apkFilePath.toLowerCase().endsWith(".apk")
                || !FileUtil.isFileExist(apkFilePath)) {
            return;
        }
        // 安装包基本信息
        PackageInfo pi = mPackageManager.getPackageArchiveInfo(apkFilePath, 0);
        if (pi == null) {
            ToastUtil.showMsg("安装包已损坏");
            return;
        }
        final String packageName = pi.packageName;
        final int versionCode = pi.versionCode;

        if (isInstalling(packageName)) {
            ToastUtil.showMsg("正在安装，请稍候..");
            return;
        }

        mInstallingPackage.add(packageName);

        Message msg = mBackgroundHandler.obtainMessage();
        msg.what = MSG_BACK_INSTALL_APK;
        Bundle data = new Bundle();
        data.putString("filePath", apkFilePath);
        data.putString("packageName", packageName);
        data.putInt("versionCode", versionCode);
        msg.setData(data);

        mBackgroundHandler.sendMessage(msg);
    }

    /**
     * 是否正在安装
     * 
     * @param packageName
     * @return
     */
    public boolean isInstalling(String packageName) {
        return mInstallingPackage.contains(packageName);
    }

    /**
     * 创建广播intent
     * 
     * @param action
     * @param state
     * @param packageName
     * @param versionCode
     * @param filePath
     * @return
     */
    public static Intent createInstallIntent(String action, int state, String packageName,
            int versionCode, String filePath) {
        Intent intent = new Intent(action);
        intent.putExtra("state", state);
        intent.putExtra("packageName", packageName);
        intent.putExtra("versionCode", versionCode);
        intent.putExtra("filePath", filePath);
        return intent;
    }

    /**
     * 普通安装成功后删除APK文件
     * 
     * @param packageName
     */
    public void deleteApkFileWhenNormalInstall(String packageName) {
        if (mNormalInstallingFile.containsKey(packageName)) {
            String filePath = mNormalInstallingFile.remove(packageName);
            FileUtil.deleteFile(filePath);
        }
    }

    // apk安装
    private void handleApkInstall(final String filePath, final String packageName,
            final int versionCode) {
        // if (!mContext.getPackageName().equals(packageName)) {
        // if (!mIsRoot) {
        // mIsRoot = ShellUtils.checkRootPermission();
        // }

        // if (mIsRoot) {
        // new Thread(new Runnable() {
        // @Override
        // public void run() {
        // // 发送开始安装通知
        // if (mOnInstallStateListener != null) {
        // mOnInstallStateListener.onStart(filePath, packageName, versionCode);
        // }
        //
        // // 安装ing
        // int result = PackageUtil.installSilent(mContext, filePath);
        //
        // boolean silentInstalled = false;
        // if (result != PackageUtil.INSTALL_SUCCEEDED) {
        // silentInstalled = PackageUtil.installNormal(mContext, filePath);
        // mInstallingPackage.remove(packageName);
        // mNormalInstallingFile.put(packageName, filePath);
        // } else if (mOnInstallStateListener != null) {
        // mInstallingPackage.remove(packageName);
        // // 发送安装结果通知
        // if (result == PackageUtil.INSTALL_SUCCEEDED || silentInstalled) {
        // mOnInstallStateListener.onSuccess(filePath, packageName,
        // versionCode);
        // } else {
        // mOnInstallStateListener.onFaile(filePath, packageName, versionCode,
        // result);
        // }
        // }
        //
        // }
        // }).start();
        //
        // } else {
        // 普通安装
        // PackageUtil.installNormal(mContext, filePath);
        // mInstallingPackage.remove(packageName);
        // mNormalInstallingFile.put(packageName, filePath);
        // }
        // } else {
        // 普通安装
        PackageUtil.installNormal(mContext, filePath);
        mInstallingPackage.remove(packageName);
        mNormalInstallingFile.put(packageName, filePath);
        // }
    }

}
